<!-- 全部订单页面1。该页面属于正常的Vue页面，正常书写代码结构，但对于订单列表这种页面来说页面性能不太好， -->
<template>
  <view v-if="shenheStatus == 0" class="page">
    <view class="order-box" v-if="order">
      <!-- 订单头部信息（订单状态） -->
      <orderHeader
        :order="order"
        @handleOrderTopBtn="handleOrderTopBtn"
      ></orderHeader>

      <view class="page-container">
        <!-- 用户信息及地址 -->
        <userInfo
          v-if="order.order_type == 0 && order.is_offline != 1"
          :order="order"
        ></userInfo>

        <!-- 物流信息 -->
        <expressLabel
          v-if="
            order.order_type == 0 &&
            order.is_delivery == 0 &&
            order.is_offline == 0
          "
          :order="order"
        ></expressLabel>

        <!-- 店铺及商品信息 -->
        <goodsDetail
          :orderitem="order"
          @buyAgain="buyAgain"
          @orderRefund="orderRefundOne"
          @commentGoods="commentGoods"
        ></goodsDetail>

        <!-- 订单明细及金额明细 -->
        <orderSummary :orderitem="order"></orderSummary>

        <!-- 底部操作按钮组 -->
        <footBtns
          :order="order"
          @handleCancleBtn="handleCancleBtn"
          @handleConfirmBtn="handleConfirmBtn"
          @handleDeleteBtn="handleDeleteBtn"
          :showRefund="showRefund"
        >
        </footBtns>
      </view>
    </view>
    <u-action-sheet
      :list="cancel_list"
      :tips="{ text: $t('mdAdmin.reason') }"
      :safe-area-inset-bottom="true"
      @click="onCancel"
      v-model="is_show_calcel"
    ></u-action-sheet>
  </view>
  <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
</template>

<script>
import Shenhe from "@/components/shenhe/shenhe";
import userInfo from "./components/order-detail/user-info.vue";
import goodsDetail from "./components/order-detail/goods-detail.vue";
import orderSummary from "./components/order-detail/order-summary.vue";
import footBtns from "./components/order-detail/foot-btns.vue";
import orderHeader from "./components/order-detail/order-header.vue";
import expressLabel from "./components/order-detail/express-label.vue";

export default {
  components: {
    userInfo,
    goodsDetail,
    orderSummary,
    footBtns,
    orderHeader,
    expressLabel,
    Shenhe
  },
  data() {
    return {
      order_id: 0,
      order: null,
      payOrderID: "",
      template_id: [],
      is_show_calcel: false,
      // 是否显示售后按钮
      showRefund: false
    };
  },
  onLoad(t) {
    this.order_id = t.id;
  },
  onShow() {
    this.getOrderInfo();
  },
  computed: {
    cancel_list() {
      return [
        {
          text: this.$t("mdAdmin.reason1"),
          color: "#333333",
          fontSize: 24
        },
        {
          text: this.$t("mdAdmin.reason2"),
          color: "#333333",
          fontSize: 24
        },
        {
          text: this.$t("mdAdmin.reason3"),
          color: "#333333",
          fontSize: 24
        },
        {
          text: this.$t("mdAdmin.reason4"),
          color: "#333333",
          fontSize: 24
        },
        {
          text: this.$t("mdAdmin.reason5"),
          color: "#333333",
          fontSize: 24
        }
      ];
    }
  },
  watch: {},
  methods: {
    onCancel: function (e) {
      this.$allrequest.order
        .preCancelOrder(
          {
            order_id: this.order_id,
            reason_id: e + 1
          },
          true
        )
        .then((res) => {
          if (res.data.resultcode == 0) {
            let msg = this.$t("order.cancle");
            if (res.data.deduct_fee && res.data.deduct_fee > 0) {
              msg + this.$t("mdAdmin.dedit") + res.data.deduct_fee;
            }
            uni.showModal({
              title: this.$t("order.prompt"),
              content: msg,
              success: (ress) => {
                if (ress.confirm) {
                  this.$allrequest.order
                    .cancelOrder(
                      {
                        order_id: this.order_id,
                        reason_id: e + 1
                      },
                      true
                    )
                    .then((r) => {
                      if (r.data.resultcode == 0) {
                        this.orderRevoke(this.order_id, false);
                      } else {
                        uni.showToast({
                          title: this.$t("mdAdmin.cancleErr"),
                          duration: 2000
                        });
                      }
                    });
                }
              }
            });
          } else {
            uni.showToast({
              title: this.$t("mdAdmin.cantCancle"),
              duration: 2000
            });
          }
        });
    },
    // 这里调用接口获取一次支付组件需要的支付类型参数及templateID
    getOrderInfo() {
      var that = this;
      this.$allrequest.mdAdmin
        .getOrderDetail({
          order_id: that.order_id
        })
        .then((res) => {
          if (res.code == 0) {
            this.order = res.data;
            let goods = this.order.goods_list || [];
            let showRefund = goods.some((item) => {
              return item.is_order_refund == 0 && item.order_refund_enable == 1;
            });
            this.showRefund = showRefund;
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
              duration: 2000
            });
            setTimeout(function () {
              uni.navigateBack({
                delta: 1
              });
            }, 1500);
          }
        });
    },

    // 点击订单顶部按钮回调
    handleOrderTopBtn(e) {
      // 当状态为未支付时，去支付
      if (e.status == -1) {
        this.gotoPay(e);
      }
    },
    // 点击订单底部按钮回调
    handleConfirmBtn(e) {
      let arr = [e.id];
      this.clerkOrder({ order_id: JSON.stringify(arr) });
    },
    clerkOrder(params) {
      uni.showLoading({
        title: this.$t("facePay.requesting")
      });
      // 待发货
      if (this.order.trade_status == 0) {
        this.$allrequest.mdAdmin.sendSelfMentionOrder(params).then((res) => {
          uni.hideLoading();
          if (!res.code) {
            uni.showToast({
              title: this.$t("admin.delivered"),
              icon: "none"
            });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none"
            });
          }
        });
      } else {
        // 已发货
        this.$allrequest.mdAdmin.clerkSelfMentionOrder(params).then((res) => {
          if (!res.code) {
            uni.showToast({
              title: this.$t("mdAdmin.clerkSuc"),
              icon: "none"
            });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none"
            });
          }
        });
      }
    },
    handleCancleBtn(e) {
      if (e.is_delivery == 1 && e.status !== -1) {
        // 同城配送订单
        this.is_show_calcel = true;
        return;
      }
      // 订单状态，-1:默认，0:待发货，1:已取消，2:已发货，3:已确认
      // 当订单状态为未支付、待发货、已发货时，可取消订单
      if (["-1", "0", "2"].includes(String(e.status))) {
        //   取消订单
        this.orderRevoke(e.id, true);
      }
      if (e.status == 3) {
        // 整个订单一起售后
        let arr = [];
        let list = this.order.goods_list;
        list.forEach((item) => {
          if (item.order_refund_enable == 1 && item.is_order_refund == 0) {
            arr.push(item);
          }
        });
        if (arr.length) {
          this.orderRefund(arr);
        } else {
          uni.showToast({
            title: this.$t("mdAdmin.noSales"),
            icon: "none"
          });
        }
      }
    },
    // 点击底部删除按钮
    handleDeleteBtn(e) {
      this.deleteOrder(e.id);
    },
    // 展示支付弹框
    gotoPay(e) {
      // 去支付
      this.payOrderID = e.id;
      // 展示支付弹框
      this.$refs.payOrderRef.setShowPopup();
    },
    // 支付成功回调
    paySuccessCb() {
      try {
        // 利用本地缓存，当返回订单列表页时，进行页面刷新
        uni.setStorageSync("needReload", "true");
      } catch (e) {
        // error
      }
      uni.navigateBack();
    },
    // 取消订单
    orderRevoke(order_id, isShowModal) {
      var that = this;
      // #ifdef MP-WEIXIN
      uni.requestSubscribeMessage({
        tmplIds: this.template_id,
        complete() {
          that.orderRevokeSubmit(order_id, isShowModal);
        }
      });
      // #endif
      // #ifndef MP-WEIXIN
      that.orderRevokeSubmit(order_id, isShowModal);
      // #endif
    },
    orderRevokeSubmit(order_id, isShowModal) {
      var that = this;
      if (isShowModal) {
        uni.showModal({
          title: this.$t("order.prompt"),
          content: this.$t("order.cancle"),
          success: function (res) {
            if (res.confirm) {
              that.$allrequest.order
                .revoke({
                  order_id: order_id
                })
                .then((res) => {
                  if (res.code == 0) {
                    try {
                      uni.setStorageSync("needReload", "true");
                    } catch (e) {
                      // error
                    }
                    uni.showToast({
                      title: res.msg,
                      icon: "none",
                      duration: 2000
                    });
                    setTimeout(() => {
                      that.$utils.toUrl("/order/order/order?status=1");
                    }, 1500);
                  } else {
                    uni.showToast({
                      title: res.msg,
                      icon: "none",
                      duration: 2000
                    });
                    return false;
                  }
                });
            } else if (res.cancel) {
            }
          }
        });
      } else {
        that.$allrequest.order
          .revoke({
            order_id: order_id
          })
          .then((res) => {
            if (res.code == 0) {
              try {
                uni.setStorageSync("needReload", "true");
              } catch (e) {
                // error
              }
              uni.navigateBack();
            } else {
              uni.showToast({
                title: res.msg,
                icon: "none",
                duration: 2000
              });
              return false;
            }
          });
      }
    },
    // 再次购买。先加购物车
    buyAgain(e) {
      // 单个加购物车
      if (e.type === "one") {
        let params = {
          goods_id: e.item.goods_id,
          num: e.item.num,
          attr: JSON.stringify(e.item.attr)
        };
        this.requestAddOneToCart(params);
      }
    },
    // 订单批量再次购买
    buyOrderAgain(list) {
      this.$allrequest.order
        .buyAgain({ goods_list: JSON.stringify(list) }, true)
        .then((res) => {
          if (res.code == 0) {
            this.$utils.toUrl("/pages/shoppingcart/shoppingcart", "switchtab");
          }
        });
    },
    // api添加单个商品到购物车
    requestAddOneToCart(params) {
      uni.showLoading({
        title: this.$t("home.loading")
      });
      this.$allrequest.goods.addCart(params).then((res) => {
        uni.hideLoading();
        uni.showToast({
          title: res.msg,
          icon: "none"
        });
        if (res.code == 0) {
          this.$utils.toUrl("/pages/shoppingcart/shoppingcart", "switchtab");
        }
      });
    },
    // 点击当个商品售后
    orderRefundOne(e) {
      if (e.order_refund_enable == 1 && e.is_order_refund == 0) {
        this.orderRefund([e]);
      }
    },
    orderRefund(list) {
      uni.setStorageSync("refund-goods", list);

      uni.navigateTo({
        url: "/order/order-refund/order-refund?id=" + this.order_id
      });
    },
    // 删除订单
    deleteOrder(order_id) {
      let that = this;
      uni.showModal({
        title: this.$t("order.prompt"),
        content: this.$t("mdAdmin.confirmCancle"),
        success: function (res) {
          if (res.confirm) {
            that.$allrequest.order
              .delete({
                order_id: order_id
              })
              .then((res) => {
                if (res.code == 0) {
                  uni.navigateBack({
                    delta: 1
                  });
                } else {
                  uni.showToast({
                    title: res.msg,
                    icon: "none",
                    duration: 2000
                  });
                  return false;
                }
              });
          } else if (res.cancel) {
          }
        }
      });
    },
    // 点击评论商品
    commentGoods(e) {
      if (e.is_comment == 1) {
        uni.navigateTo({
          url:
            "/order/order-comment/order-comment?id=" +
            this.order_id +
            "&goods_info=" +
            JSON.stringify(e)
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f2f2f2;
}

.page-container {
  position: relative;
  z-index: 10;
  top: 0rpx;
}

.order-box {
  background-color: #f2f2f2;
}

.flex-grow-1 {
  display: flex;
}

.flex-between {
  justify-content: space-between;
}

view {
  font-size: 32rpx;
}

.order-status {
  padding: 20rpx;
  line-height: 80rpx;
  font-size: 36rpx;
  background: #f29100;
  color: #ffffff;
}

.order-model {
  background: #ffffff;
  padding: 20rpx;
  margin-bottom: 16rpx;
}

.order-address > view {
  background: #ffffff;
  padding: 10rpx 0;
}

.order-offline {
  display: flex;
  justify-content: space-between;
  align-items: center;

  > view > view {
    padding: 8rpx;
  }
}

.order-info > view {
  padding: 8rpx;
}

.order-price > view {
  padding: 6rpx;
}

.goods-item {
  display: flex;

  .goods-img {
    width: 200rpx;
    height: 200rpx;
    overflow: hidden;

    > image {
      width: 200rpx;
      height: 200rpx;
    }
  }

  .goods-info {
    width: 550rpx;
    padding-left: 16rpx;
    box-sizing: border-box;
  }
}

.refund-btn {
  float: right;
  height: 60rpx;
  border: 1rpx solid #bbb;
  padding: 0 30rpx;
  border-radius: 10rpx;
  margin-top: 20rpx;
  line-height: 60rpx;
}

.refund-text {
  float: right;
  display: inline-block;
  margin-top: 20rpx;
}
</style>
